#!/usr/bin/env python
#coding:utf-8
import time
import urllib.parse,urllib.request
import json
import logging
import re
import qrcode
from pyqrcode import QRCode
import sys
import subprocess
import os

class Wechat:
    def __init__(self):
        self.appid = 'wx782c26e4c19acffb'
        self.lang = 'zh_CN'
        self.uuid = ''
        self.commandLineQRCode = False
        self.saveFolder = os.path.join(os.getcwd(), 'saved')
        self.saveSubFolders = {'webwxgeticon': 'icons', 'webwxgetheadimg': 'headimgs', 'webwxgetmsgimg': 'msgimgs',
                               'webwxgetvideo': 'videos', 'webwxgetvoice': 'voices', '_showQRCodeImg': 'qrcodes'}

    def __str__(self):
        pass

    def _get_uid(self):
        cur_time = int(time.time())
        url = "https://login.weixin.qq.com/jslogin"
        params = {
            'appid':self.appid,
            'lang':self.lang,
            '_':cur_time,
            'fun':'new'
        }
        data = self._post(url=url,params=params).decode('utf-8')
        print("=====%s========"%data)
        if data == '':
            return False
        m = re.search(r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+)==";',data)
        code = m.group(1)
        print("=====code:%s======"%code)
        if code == '200':
            self.uuid = m.group(2)
            return True
        return False

    def _get_QRCode(self):
        print("======sys:%s========"%sys.platform)
        if sys.platform.startswith('win'):
            self._showQRCodeImg('win')
        elif sys.platform.find('darwin') >=0:
            self._showQRCodeImg('macos')
        else:
            self._str2qr('https://login.weixin.qq.com/l/' + self.uuid)

    def _showQRCodeImg(self, str):
        if self.commandLineQRCode:
            print("=======%s======="%self.uuid)
            qrCode = QRCode('https://login.weixin.qq.com/l/' + self.uuid)
            self._showCommandLineQRCode(qrCode.text(1))
        else:
            url = 'https://login.weixin.qq.com/qrcode/' + self.uuid
            print("=====url:%s=====" % url)
            params = {
                't': 'webwx',
                '_': int(time.time())
            }

            data = self._post(url, params, False)
            if data == '':
                return
            print("=====data:%s====="%data)
            QRCODE_PATH = self._saveFile('qrcode.jpg', data, '_showQRCodeImg')
            if str == 'win':
                os.startfile(QRCODE_PATH)
            elif str == 'macos':
                subprocess.call(["open", QRCODE_PATH])
            else:
                return
    def _showCommandLineQRCode(self, qr_data, enableCmdQR=2):
        try:
            b = u'\u2588'
            sys.stdout.write(b + '\r')
            sys.stdout.flush()
        except UnicodeEncodeError:
            white = 'MM'
        else:
            white = b
        black = '  '
        blockCount = int(enableCmdQR)
        if abs(blockCount) == 0:
            blockCount = 1
        white *= abs(blockCount)
        if blockCount < 0:
            white, black = black, white
        sys.stdout.write(' ' * 50 + '\r')
        sys.stdout.flush()
        qr = qr_data.replace('0', white).replace('1', black)
        sys.stdout.write(qr)
        sys.stdout.flush()

    def _str2qr(self, str):
        print(str)
        qr = qrcode.QRCode()
        qr.border = 1
        qr.add_data(str)
        qr.make()
        # img = qr.make_image()
        # img.save("qrcode.png")
        #mat = qr.get_matrix()
        #self._printQR(mat)  # qr.print_tty() or qr.print_ascii()
        qr.print_ascii(invert=True)

    def _saveFile(self, filename, data, api=None):
        fn = filename
        if self.saveSubFolders[api]:
            dirName = os.path.join(self.saveFolder, self.saveSubFolders[api])
            if not os.path.exists(dirName):
                os.makedirs(dirName)
            fn = os.path.join(dirName, filename)
            logging.debug('Saved file: %s' % fn)
            with open(fn, 'wb') as f:
                f.write(data)
                f.close()
        return fn

    def _post(self,url,params,jsonfmt=False):
        if jsonfmt:
            data = json.dumps(params).encode()
            req = urllib.request.Request(url=url,data=data)
            req.add_header('ContentType', 'application/json; charset=UTF-8')
        else:
            req = urllib.request.Request(url=url,data=urllib.parse.urlencode(params).encode('utf-8'))
        try:
            response = urllib.request.urlopen(req)
            data = response.read()
            if jsonfmt:
                return json.loads(data.decode('utf-8'))
            return data
        except Exception:
            import traceback
            logging.error('generic exception: ' + traceback.format_exc())
        return ''

    def _get(self,url,timeout):
        request = urllib.request.Request(url=url)
        request.add_header('Referer', 'https://wx.qq.com/')
        try:
            if timeout:
                response = urllib.request.urlopen(request, timeout=timeout)
            else:
                response = urllib.request.urlopen(request)
            #response = urllib.request.urlopen(request,timeout=timeout) if timeout else response = urllib.request.urlopen(request)
            data = response.read()
            return data
        except Exception:
            import traceback
            logging.error('generic exception: ' + traceback.format_exc())
        return ''
    def run(self):
        flag = self._get_uid()
        print("======flag:%s========="%flag)
        if flag:
            self._get_QRCode()
            print("Get uuid sucess")
        else:
            print("Get uuid false")


obj = Wechat()
obj.run()


